package com.nl.controller.sms5g.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.nl.controller.common.exception.SmsException;
import com.nl.controller.common.global.GlobalConstants;
import com.nl.controller.common.service.CommonService;
import com.nl.controller.common.util.BaseResult;
import com.nl.controller.common.util.MD5;
import com.nl.controller.sms5g.bean.NewTemplateSyncResp;
import com.nl.controller.sms5g.bean.Rets;
import com.nl.controller.sms5g.bean.Sms5gTemplateInfo;
import com.nl.controller.sms5g.bean.UploadFileInfo;
import com.nl.controller.sms5g.bean.bo.*;
import com.nl.controller.sms5g.bean.po.QueryRangePo;
import com.nl.controller.sms5g.bean.po.QueryRangeResp;
import com.nl.controller.sms5g.bean.po.SendRangeSynchronizationResp;
import com.nl.controller.sms5g.mapper.Sms5gSendRangeMapper;
import com.nl.controller.sms5g.mapper.Sms5gSignatureMapper;
import com.nl.controller.sms5g.mapper.Sms5gTemplateMapper;
import com.nl.controller.sms5g.service.Sms5gSendRangeService;
import com.nl.controller.sms5g.service.Sms5gTemplateService;
import com.nl.controller.web.bean.SmsBaseStation;
import com.nl.controller.web.global.GlobalConst;
import com.nl.controller.web.mapper.SmsBaseStationMapper;
import com.nl.controller.web.util.GZipUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.*;

/**
 * @desc 5G多媒体项目发送范围
 * @return null
 * @author l
 * @date 2021/6/17 17:43
 */
@Service
@Slf4j
public class Sms5gSendRangeServiceImpl implements Sms5gSendRangeService {

    @Autowired
    private SmsBaseStationMapper smsBaseStationMapper;

    @Autowired
    private Sms5gSendRangeMapper sms5gSendRangeMapper;
    /**
     * @desc 5G多媒体项目圈划范围基站信息
     * @param insertBaseStationBo
     * @return com.nl.controller.common.util.BaseResult
     * @author l
     * @date 2021/6/17 17:48
     */
    @Override
    public BaseResult createRangeStation(InsertBaseStationBo insertBaseStationBo) {
        BaseResult baseResult = BaseResult.newFailInstance();
        List<String> list = new ArrayList<>();
        String[] stationArry  = null;
        String stationIds = insertBaseStationBo.getStationIds();
        String cityId = insertBaseStationBo.getCityId();
        String mgrId = insertBaseStationBo.getMgrId();
        if(!StringUtils.isEmpty(stationIds)){
            stationArry = stationIds.split(",");
            list = Arrays.asList(stationArry);
        }

        try {
            for (int i = 0; i < list.size(); i++) {
                SmsBaseStation baseStation = new SmsBaseStation();
                baseStation.setCityId(cityId);
                baseStation.setId(mgrId);
                baseStation.setStationId(list.get(i));
                String unique = "1";
                try {
                    unique = smsBaseStationMapper.checkBaseStation(baseStation);
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("校验信息重复出现异常");
                }
                if (unique.equals("0")) {
                    smsBaseStationMapper.addSmsBaseStation(baseStation);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            baseResult.setRetCode(GlobalConstants.EXCEPTION_STRING);
            baseResult.setRetMsg("新增5G项目发送范围基站发生异常");
        }
        return baseResult;
    }
    
    /**
     * @desc 查询5g多媒体项目发送范围
     * @param req 
     * @return com.nl.controller.common.util.BaseResult<java.util.List<com.nl.controller.sms5g.bean.po.QueryRangeResp>>
     * @author l
     * @date 2021/6/18 15:05
     */
    @Override
    public BaseResult<QueryRangeResp> queryRange(QuerySendRangeBo req) {
        BaseResult<QueryRangeResp> result = BaseResult.newFailInstance();
        try {
            QueryRangePo rangePo = sms5gSendRangeMapper.queryRange(req.getMgrId());
            if(!Objects.isNull(rangePo)){
                List<String> latitudeAndLongitudes = JSON.parseArray(rangePo.getRangeValue(),String.class);
                QueryRangeResp queryRangeResp = new QueryRangeResp();
                queryRangeResp.setMgrId(req.getMgrId());
                queryRangeResp.setRangeValue(latitudeAndLongitudes);
                result.setData(queryRangeResp);
            }
            result.setRetCode(GlobalConstants.SUCCESS_STRING);
            result.setRetMsg("查询项目发送范围成功");
        } catch (Exception e) {
            result.setRetMsg("查询项目发送范围异常："+e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public BaseResult<Object> updateRange(UpdateRangeReq req) {
        BaseResult<Object> result = BaseResult.newFailInstance();
        try {
            String mgrId = req.getMgrId();
            QueryRangePo rangePo = sms5gSendRangeMapper.queryRange(req.getMgrId());
            //若有范围则变更，没有范围则新增
            if(!Objects.isNull(rangePo)){
                sms5gSendRangeMapper.updateRange(mgrId,req.getRange());
            }else{
                CreateRangeReq createRangeReq = new CreateRangeReq();
                createRangeReq.setMgrId(req.getMgrId());
                createRangeReq.setRange(req.getRange());
                sms5gSendRangeMapper.createRange(createRangeReq);
            }
            SendRangeSynchronizationResp sendRangeSynchronizationResp = new SendRangeSynchronizationResp();
            sendRangeSynchronizationResp.setMgrId(mgrId);
            sendRangeSynchronizationResp.setStationIds(req.getStationIds());
            int insertResult = addStationTemp(sendRangeSynchronizationResp);
            result.setRetCode(GlobalConstants.SUCCESS_STRING);
            result.setRetMsg("更新发送范围成功");
        } catch (Exception e){
            result.setRetMsg("更新基站异常："+e.getMessage());
        }
        return result;
    }

    @Override
    public BaseResult<Object> createRange(CreateRangeReq req) {
        BaseResult<Object> result = BaseResult.newFailInstance();
        try {
            String mgrId = req.getMgrId();
            sms5gSendRangeMapper.createRange(req);
            SendRangeSynchronizationResp sendRangeSynchronizationResp = new SendRangeSynchronizationResp();
            sendRangeSynchronizationResp.setMgrId(mgrId);
            sendRangeSynchronizationResp.setStationIds(req.getStationIds());
            int insertResult = addStationTemp(sendRangeSynchronizationResp);
            result.setRetCode(GlobalConstants.SUCCESS_STRING);
            result.setRetMsg("更新发送范围成功");
        } catch (Exception e){
            result.setRetMsg("更新基站异常："+e.getMessage());
        }
        return result;
    }

    private Integer addStationTemp(SendRangeSynchronizationResp resp){
        int stationCount = 0;
        List<String> regionList=new ArrayList();
        String id =  resp.getMgrId();
        //先删除原有基站信息
        int deleteResult = smsBaseStationMapper.deleteBaseStation(id);
        String cityId = sms5gSendRangeMapper.findMgrCityId(id);
        String regionId = smsBaseStationMapper.getMaxRegionId(cityId)+"";
        List<String> stationIds = Arrays.asList(resp.getStationIds().split(","));
        if(!StringUtils.isEmpty(resp.getStationIds())){
            stationCount = stationIds.size();
        }
        List<SmsBaseStation> list = new ArrayList<>();
        if (!CollectionUtils.isEmpty(stationIds)){
            for ( String stationId :stationIds ) {
                if(!StringUtils.isEmpty(stationId)){
                    list.add(new SmsBaseStation(id,regionId,"5g项目基站区域",stationId,"5g项目基站"+stationId,cityId));
                }
            }
        }

        for (int i = 0; i < list.size(); i++) {
            SmsBaseStation baseStation = list.get(i);
            String unique = "1";
            try {
                unique = smsBaseStationMapper.checkBaseStation(baseStation);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("校验信息重复出现异常");
            }
            if (unique.equals("0")) {
                try {
                    smsBaseStationMapper.addSmsBaseStation(baseStation);
                    stationCount++;

                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("导入基站信息异常" + baseStation.getStateName());
                    throw new SmsException("导入基站信息");
                }
            }
        }

        return stationCount;
    }
}
